package com.ct.gd.passport.service;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.ct.gd.passport.common.constants.Config;
import com.ct.gd.passport.domain.PassportGoApply;
import com.fuckhtc.gson.Gson;
import com.fuckhtc.gson.reflect.TypeToken;
import com.up91.common.android.cache.CacheBuilder;
import com.up91.common.android.cache.CacheBuilder.CacheType;
import com.up91.common.android.cache.L2Cache;
import com.up91.common.android.helper.L;

public class PassportRecordFacade {

	public static final PassportRecordFacade instance = new PassportRecordFacade();

	private L2Cache<String, String> cache = null;
	private ArrayList<PassportGoApply> serialList = null;
	TypeToken<List<PassportGoApply>> typeToken = new TypeToken<List<PassportGoApply>>() {
	};

	private static final String CACHE_LIST = "pplist.db";

	private PassportRecordFacade() {
		CacheBuilder<String, String> builder = new CacheBuilder<String, String>();
		cache = (L2Cache<String, String>) builder.setCacheName(CACHE_LIST).setDiskPath(Config.CACHE_PATH).setType(CacheType.DEFAULT_L2)
				.setMemMaxSize(10).create();
		String json = cache.get("list");
		if (json != null) {
			L.i("PassportRecordListInit", json);
			serialList = new Gson().fromJson(json, typeToken.getType());
		} else {
			serialList = new ArrayList<PassportGoApply>();
		}
	}

	public void addPassportRecord(PassportGoApply apply) {
		if (apply != null && apply.getSerial() != null) {
			int idx = serialList.indexOf(apply);
			if (idx >= 0) {
				serialList.remove(idx);
			}
			if (serialList.size() >= 10) {
				serialList.remove(9);
			}
			serialList.add(0, apply);
			String list = new Gson().toJson(serialList, typeToken.getType());
			Log.i("PassportRecordList", list);
			cache.put("list", list);
		}
	}

	public ArrayList<PassportGoApply> getPassportRecordList() {

		return serialList;
	}

	public PassportGoApply getPassportGoApply(String id) {
		for (PassportGoApply apply : serialList) {
			if (apply.getSerial().equals(id)) {
				return apply;
			}
		}
		return null;
	}

}
